package protocol;

/**
 * Represents the CTF packet format for client-server communication.  
 * Requests from client to server are header-only.
 * Responses from server to client contain a body.
 * 
 * @author WHOMP
 * @since Java 1.6
 */
public class CtfPacket {
	
	/** Instance Variables */
	CtfHeader header;
	/* Contains the msg in bytes from the server to the client.
	 * Initialized to an empty array to be set if needed in constructors. */
	byte[] body = new byte[0];
	
	/**
	 * Constructor for client use.
	 * @param header
	 */
	public CtfPacket( CtfHeader header ) {
		this.header = header;
	}

	/**
	 * Constructor for a whole packet.
	 * @param header
	 * @param msg
	 */
	public CtfPacket( CtfHeader header, byte[] msg ) {
		this.header = header;
		this.body = msg;
	}
	
	/**
	 * Constructor for client use: header only
	 * @param sender
	 * @param msgType
	 * @param gameState
	 */
	public CtfPacket( int sender, int msgType, int gameState ) {
		this.header = new CtfHeader( sender, msgType, gameState);
	}
	
	public CtfPacket( int sender, int msgType, int gameState, byte[] body ) {
		this.header = new CtfHeader( sender, msgType, gameState );
		this.body = body;
	}
	
	/* Accessors */
	public CtfHeader getHeader() { return header; }
	public byte[] getBody() { return body; }
	
	/* set the message field */
	public void setBody( byte[] msg ) {
		this.body = msg;
	}

	/* byte array representation for transmission purposes*/
	public byte[] toNetworkByteArray() {
		byte[] headerInBytes = this.header.toNetworkByteArray();
		byte[] packetInBytes = new byte[ headerInBytes.length + body.length ];
		System.arraycopy(headerInBytes, 0, packetInBytes, 0, headerInBytes.length);
		System.arraycopy(body, 0, packetInBytes, headerInBytes.length, body.length);
		return packetInBytes;
	}
	
	/* string representation for transmission purposes*/
	public String toString() {
		if ( this.body == null ) return header.toString();
		return header.toString() + new String( this.body );
	}
	
}





